import { downloadFile } from '@api/city-medical'
import { ElMessage } from 'element-ui'
// 将id，pid数据处理为tree型数据
export const createTreeData = (
  arr = [],
  id = 'id',
  pid = 'pid',
  children = 'children'
) => {
  if (!arr.length) return []
  let res = [],
    hash = {},
    i = 0,
    j = 0,
    len = arr.length
  for (; i < len; i++) {
    // 将所有的id对应的数据，放置在hash[id] 上
    hash[arr[i][id]] = arr[i]
  }
  for (; j < len; j++) {
    let a = arr[j],
      hashPid = hash[a[pid]] // pid是否在hash[id]存在
    if (hashPid) {
      // 存在
      !hashPid[children] && (hashPid[children] = []) // 没有children，初始化children属性
      hashPid[children].push(a)
    } else {
      res.push(a)
    }
  }
  return res
}

// 在树形数据中，获取指定key为value的数据
export const getUniqueFromTree = (tree = [], key, value) => {
  let res = null
  const loop = (tree, key) => {
    if (!tree.length) return null
    else {
      for (let i = 0, len = tree.length; i < len; i++) {
        if (tree[i][key] === value) {
          res = tree[i]
          break
        } else if (tree[i].children) {
          loop(tree[i].children, key)
        } else {
          continue
        }
      }
    }
  }

  loop(tree, key)

  return res
}

//  json to dom
export const jsonToDom = (json) => {
  const {
    tagName = 'div',
    children = [],
    classList = [],
    id = '',
    text = '',
    style = '',
    title,
  } = json
  const dom = document.createElement(tagName)
  dom.classList = classList.join(' ')
  dom.id = id
  dom.innerText = text
  dom.style = style
  dom.title = title
  if (children && children.length > 0) {
    children.forEach((json) => {
      dom.appendChild(jsonToDom(json))
    })
  }
  return dom
}

export function loadFile(id, name) {
  downloadFile(id)
    .then((res) => {
      if (res) {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `${name}`)
        document.body.appendChild(link)
        link.click()
      }
    })
    .catch(() => {
      ElMessage.error('下载失败')
    })
}

// 指标内容转换为tree
export function quotaTotree(quotaList) {
  return quotaList.map((quota) => {
    return {
      ...quota,
      children: [
        ...viewFormat(quota.indexViewDataInfoVo.indexViewDatasVos, quota.name),
        ...quota.indexViewDataInfoVo.indexDataInfoVos,
      ],
      type: 'quota',
      disabled: true,
    }
  })
}

// 维度和下面指标格式化
export function viewFormat(views, dimensionName) {
  return views
    ? views.map((view) => {
        return {
          ...view.indexViewInfo,
          children: view.indexDataInfoVos
            ? view.indexDataInfoVos.map((i) => {
                return {
                  ...i,
                  leaf: true,
                  parentData: {
                    type: 'view',
                    pkid: view.indexViewInfo.pkid,
                  },
                }
              })
            : [],
          type: 'view',
          dimensionName,
          disabled: true,
        }
      })
    : []
}

const REGEX_PARSE =
  /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/
const REGEX_FORMAT =
  /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|SSS/g
const defaultMeridiem = (hours, minutes, isLowercase, hasPeriod) => {
  let m = hours < 12 ? 'AM' : 'PM'
  if (hasPeriod) m = m.split('').reduce((acc, curr) => (acc += `${curr}.`), '')
  return isLowercase ? m.toLowerCase() : m
}

export const formatDate = (date, formatStr, options = {}) => {
  var _a
  const years = date.getFullYear()
  const month = date.getMonth()
  const days = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()
  const milliseconds = date.getMilliseconds()
  const day = date.getDay()
  const meridiem = (_a = options.customMeridiem) != null ? _a : defaultMeridiem
  const matches = {
    YY: () => String(years).slice(-2),
    YYYY: () => years,
    M: () => month + 1,
    MM: () => `${month + 1}`.padStart(2, '0'),
    MMM: () => date.toLocaleDateString(options.locales, { month: 'short' }),
    MMMM: () => date.toLocaleDateString(options.locales, { month: 'long' }),
    D: () => String(days),
    DD: () => `${days}`.padStart(2, '0'),
    H: () => String(hours),
    HH: () => `${hours}`.padStart(2, '0'),
    h: () => `${hours % 12 || 12}`.padStart(1, '0'),
    hh: () => `${hours % 12 || 12}`.padStart(2, '0'),
    m: () => String(minutes),
    mm: () => `${minutes}`.padStart(2, '0'),
    s: () => String(seconds),
    ss: () => `${seconds}`.padStart(2, '0'),
    SSS: () => `${milliseconds}`.padStart(3, '0'),
    d: () => day,
    dd: () => date.toLocaleDateString(options.locales, { weekday: 'narrow' }),
    ddd: () => date.toLocaleDateString(options.locales, { weekday: 'short' }),
    dddd: () => date.toLocaleDateString(options.locales, { weekday: 'long' }),
    A: () => meridiem(hours, minutes),
    AA: () => meridiem(hours, minutes, false, true),
    a: () => meridiem(hours, minutes, true),
    aa: () => meridiem(hours, minutes, true, true),
  }
  return formatStr.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match]())
}

export const baseFileUrl =
  process.env.NODE_ENV === 'development'
    ? 'http://192.168.3.28:3117'
    : // @ts-ignore
      // disable-eslint next-line no-undef
      window.BASE_FILE_URL
